# coding: utf-8

from optparse import OptionParser
from lxml import etree
import glob
import os
import simplejson
from copy import deepcopy

if __name__ == "__main__":
    # Setup the parser
    parser = OptionParser()
    parser.add_option("-i", "--input", type="string", dest="input", default = '/usr/share/mime')
   
    # Parse the options
    (options, args) = parser.parse_args()
    
    formatTypes = {}
    
    print options.input
    for xml_File in glob.glob(os.path.join(options.input, '*/*.xml')) + glob.glob('*.xml'):
        print xml_File
        doc = etree.parse(xml_File)
        ns = {'c':doc.getroot().nsmap[None]}
        mime_elements = [doc.getroot()]#doc.find('mime-type')
        if mime_elements[0].tag.find('mime-type') == -1:
            mime_elements = mime_elements[0].xpath('c:mime-type', namespaces=ns)
        for mime_element in mime_elements:
            mime =  mime_element.get('type')
            globs = mime_element.xpath('c:glob', namespaces=ns)
            ext = globs[0].get('pattern', '').replace('*', '') if len(globs) else ''
            type = mime[:mime.find('/')].capitalize()
            if type == 'Inode':
                break
            if not type in formatTypes:
                formatTypes[type] = {}
            for comment in mime_element.xpath('c:comment', namespaces=ns):
                if comment.xpath('not(@xml:lang)', namespaces={'xml':'http://www.w3.org/XML/1998/namespace'}):
                    formatTypes[type][mime] = (comment.xpath('text()')[0].replace('\'', u'`'), ext, )
                    break
                #TODO: write out translations here. (remove break above)
                #else:
                #   lc = comment.xpath('@xml:lang', namespaces={'xml':'http://www.w3.org/XML/1998/namespace'})[0]
                #   translation = comment.xpath('text()')[0]
                #   print lc, translation

    
    i = 0
    j = 0
    data = []
    FORMATTYPE = {'pk': 0, 'model':'assets.FormatType', 'fields': {'name': ''}}
    FORMAT = {'pk': 0, 'model':'assets.Format', 'fields': {'name':'', 'type':'', 'legible':'', 'ext':''}}
    for type, formats in formatTypes.items():
        i += 1
        format_type = deepcopy(FORMATTYPE)
        format_type['pk'] = str(i)
        format_type['fields']['name'] = type
        data.append(format_type)
        
        for mime, args in formats.items():
            legible, ext = args
            j += 1
            #j, Q(mime), i, Q(legible.encode( "utf-8" )), Q(ext))
            format = deepcopy(FORMAT)
            format['pk'] = str(j)
            format['fields']['name'] = mime
            format['fields']['type'] = str(i)
            format['fields']['legible'] = legible.encode( "utf-8" )
            format['fields']['ext'] = ext
            data.append(format)
		
    f = open('formats.json', 'w')
    d = simplejson.dumps(data, indent=2)
    f.write(d)
    f.close()
